// \u4e00-\u9fa5] 中文验证规则

import validate from 'wechat-validate'

Page({
  behaviors: [validate],
  rules: {
    name: [
      { required: true, message: '业主姓名不能为空!' },
      { pattern: /^[\u4e00-\u9fa5]{2,5}$/, message: '业主姓名只能为中文!' }
    ],
    mobile: [
      { required: true, message: '业主手机号不能为空!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号!' }
    ],
    idcardFrontUrl: [{ required: true, message: '请上传身份证国徽面!' }],
    idcardBackUrl: [{ required: true, message: '请上传身份证照片面!' }]
  },
  data: {
    // 设置为undefined，给后端传递的时候，不会传过去
    id: undefined,
    point: '',
    building: '',
    room: '',
    mobile: '',
    gender: '',
    name: '',
    idcardFrontUrl: '/static/images/avatar_1.jpg',
    idcardBackUrl: '/static/images/avatar_2.jpg'
  },
  // goList () {
  //   wx.reLaunch({
  //     url: '/house_pkg/pages/list/index'
  //   })
  // },
  removePicture (ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({ [type]: '' })
  },
  onLoad ({ point, building, room, id }) {
    if (id) {
      // 有id是编辑
      this.getDetail(id)
      wx.setNavigationBarTitle({
        title: '编辑房屋信息'
      })
    } else {
      // 没id是新增
      this.setData({ point, building, room })
      wx.setNavigationBarTitle({
        title: '添加房屋信息'
      })
    }
  },
  // 获取详情
  async getDetail (id) {
    const { data } = await wx.http.get(`/room/${id}`)
    console.log(data)
    this.setData({
      ...data
    })
  },
  async onSubmit () {
    const isValidate = this.validate()
    // wx.utils.toast(isValidate
    console.log(isValidate)
    if (!isValidate) {
      return
    }
    // eslint-disable-next-line no-unused-vars
    const { __webviewId__, status, ...body } = this.data
    await wx.http.post('/room', body)
    // 回退列表页，后退4级，中间的路由都销毁
    wx.navigateBack({ delta: body.id ? 2 : 4 })
  },
  async choosePicture (e) {
    const { type } = e.mark
    const { tempFiles } = await wx.chooseMedia({
      type: ['image'],
      count: 1
    })
    console.log(tempFiles[0].tempFilePath)
    if (tempFiles[0].size > 2 * 1024 * 1024) {
      return wx.utils.toast('图片太大')
    }
    const res = await wx.http.upload('/upload', {
      name: 'file',
      filePath: tempFiles[0].tempFilePath
    })
    console.log(res)
    this.setData({
      // 对象key，用[]插值语法，动态设置key值
      [type]: res.data.url
    })
  }
})
